package com.iqismart.shorturl.listener;

import com.iqismart.shorturl.cache.UrlCountCache;
import com.iqismart.shorturl.service.LogService;
import com.iqismart.shorturl.service.UserService;
import com.iqismart.shorturl.vo.RegisterRequest;
import com.iqismart.shorturl.vo.UserInfoResponse;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @Description
 * @Auther sty
 * @createTime 2019/10/14 01:45
 */
@Component
@Order(1)
public class InitDataListener implements ApplicationRunner {
    @Autowired
    private LogService logService;

    @Autowired
    private UserService userService;

    public InitDataListener() {
    }

    public void run(ApplicationArguments args) throws Exception {

        {
            try {
                final RegisterRequest registerRequest = new RegisterRequest();
                registerRequest.setUsername("admin");
                registerRequest.setPassword("111111");
                registerRequest.setPasswordConfirm("111111");
                userService.register(registerRequest);
            } catch (Exception e) {
            }
        }
        try {
            UrlCountCache.todayAdd.set(logService.getTodayAdd());
            UrlCountCache.todayGet.set(logService.getTodayGet());
            UrlCountCache.totalAdd.set(logService.getTotalAdd());
            UrlCountCache.totalGet.set(logService.getTotalGet());

            List<UserInfoResponse> newUserList = userService.getNewUserList();
            if(CollectionUtils.isEmpty(newUserList)){
                final RegisterRequest registerRequest = new RegisterRequest();
                registerRequest.setUsername(RandomStringUtils.random(6));
                registerRequest.setPassword("111111");
                registerRequest.setPasswordConfirm("111111");
                userService.register(registerRequest);
                newUserList = userService.getNewUserList();
            }
            final UserInfoResponse userInfoResponse = newUserList.get(0);
            UrlCountCache.map.put("newUid",userInfoResponse.getId()+"");
            UrlCountCache.map.put("newUsername",userInfoResponse.getUsername()+"");

            UrlCountCache.map.put("randomOnlineUserCount",13+"");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


}
